<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>搜索框输入文字自动提示</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css" />
    <style type="text/css">
      .container {
        padding-top: 150px;
      }
      .list-group {
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="请输入搜索关键字" id="search" />
        <ul class="list-group" id="list-box"></ul>
      </div>
    </div>
    <script src="/js/template-web.js"></script>
    <script src="/js/ajax.js"></script>
    <script type="text/html" id="tpl">
      {{each res}}
      <li class="list-group-item">{{$value}}</li>
      {{/each}}
    </script>
    <script>
      let searchInp = document.getElementById('search')
      let listBox = document.getElementById('list-box')
      let timer = null
      searchInp.oninput = function () {
        // 获得用户输入的内容
        let k = this.value
        clearTimeout(timer)
        if (k.trim().length == 0) {
          // 将提示下拉框隐藏
          listBox.style.display = 'none'
          console.log('k')
          // 阻止程序向下执行
          return
        }
        timer = setTimeout(function () {
          ajax({
            type: 'get',
            url: 'http://localhost:3000/searchAutoPrompt',
            data: {
              key: k
            },
            success(res) {
              console.log(res)
              let html = template('tpl', { res: res })
              listBox.innerHTML = html
              listBox.style.display = 'block'
            }
          })
        }, 400)
      }
    </script>
  </body>
</html>
